package com.totoro.controller;

import com.totoro.exception.BusinessRuntimeException;
import com.totoro.exception.ResultCode;
import com.totoro.pojo.*;

import com.totoro.service.*;
import lombok.SneakyThrows;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author TOTORO
 * @date 2021/6/14 12:47
 * 处理所有Spu Sku 属性的控制器
 */
@Controller
@RequestMapping("/attr")
public class AttributeController {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private AttributeService attributeService;
    @Autowired
    private UserService userService;
    @Autowired
    private ProductService productService;
    @Autowired
    SellerService sellerService;
    @Autowired
    ShopService shopService;


    /**
     * 获取akid-spuid 对应的值
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("/get_spu_value")
    public String getSpuValue(@RequestParam("key") String id){
        int akid = Integer.parseInt(id);
        String values = attributeService.findSpuValue(akid);
        // 通过split，将该值分割
        String[] strings = values.split(",");
        JSONArray jsonArray = JSONArray.fromObject(strings);
        return jsonArray.toString();
    }

    /**
     * 获取所有的商品属性 -- 正式发布商品
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/publish", method = RequestMethod.POST)
    public String getAllAttr(@RequestParam("title") String title,@RequestParam("spuJson") String spuJson, @RequestParam("skuJson") String skuJson,
                             @RequestParam("moneys[]") double[] productPrices, @RequestParam("counts[]") Integer[] productCounts, @RequestParam("subStock") int subStock,
                             @RequestParam("status") int status, @RequestParam("extracts[]") String[] extracts,
                             @RequestParam("editorHtml") String html, @RequestParam("cid") int cid, HttpServletRequest request, HttpSession session){
        if(null == title || null == spuJson || null == skuJson || null == productCounts || null == productPrices || null == extracts || null == html || 0 == cid){
            throw new BusinessRuntimeException(ResultCode.PARAM_ERROR);
        }

        MultipartFile[] files = (MultipartFile[]) session.getAttribute("files");
        if(files== null || files.length<=0){
            return "no";
        }
        User user = (User) session.getAttribute("user");

        // 先添加产品，将产品打包成对象
        Product product = new Product();
        product.setProductName(title);
        product.setSpuAttrList(spuJson);
        product.setProductDetailHtml(html);
        // 计算所有sku规格的总数量
        int productCount = 0;
        for (int i = 0; i < productCounts.length; i++) {
            productCount+=productCounts[i];
        }
        product.setProductCount(productCount);
        // 减库存方式
        product.setItMethod(subStock);
        // 计算最低价格
        Arrays.sort(productPrices);
        double nowPrice = productPrices[0];
        product.setNowPrice(nowPrice);
        // 是否立即上架
        product.setIsLanunched(status);
        // 如果立即上架，则创建发布时间
        if(status == 1){
            product.setPublishTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        }

        product.setCid(cid);
        // 获取卖家Id
        Seller seller = sellerService.findSellerIdByUserId(user.getUserId());
        int slid = seller.getId();
        product.setSlid(slid);
        // 获得店铺id
        Shop shop = shopService.findShopBySlid(slid);
        int shopId = shop.getId();
        product.setSid(shopId);
        product.setScid(1);
        String belongId = "";
        String thatPath = categoryService.byIdFindCategory(cid).getPath();
        if(thatPath.split(",").length == 1){
            belongId = thatPath;
        } else{
            belongId = thatPath.split(",")[1];
        }
        product.setBelongCategoryId(Integer.parseInt(belongId));
        productService.addProduct(product);



        // 添加sku规格属性组
        JSONArray ay= JSONArray.fromObject(skuJson);
        productService.addProductSkus(product.getId(), ay, productCounts, productPrices);

        // 添加商品图片
        productService.addProductImages(product.getId(), files, request);

        // 判断该产品是否有月成交记录，如果没有则添加
        ProductMonthDeal productMonthDeal = new ProductMonthDeal();
        productMonthDeal.setPid(product.getId());
        productMonthDeal.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        ProductMonthDeal productMonthDeal1 = productService.findNowMonthIsHaveProductDeal(productMonthDeal);
        if(null == productMonthDeal1){
            Integer[] integers = {product.getId()};
            productService.addProductMonthDeal(integers);
        }

        return "ok";
    }

    /**
     * 上传分类图
     * @param files
     * @param request
     * @return
     */
    @SneakyThrows
    @RequestMapping(value = "/uploadCategoryImg", method = RequestMethod.POST)
    public String uploadCategoryImg(@RequestParam("categoryImg") MultipartFile[] files, @RequestParam("imgName") String[] imgNames, HttpServletRequest request){
        if(files.length > 0){
            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i];
                String uploadPath = request.getSession().getServletContext().getRealPath("/");
                System.out.println(uploadPath);
                File path =  new File(uploadPath);
                if(path == null){ path.mkdirs();}
                String filename = imgNames[i].substring(1, imgNames[i].length());
                // 通过MultipartFile的transferTo(File dest)这个方法来直接转存文件到指定的路径
                file.transferTo(new File(uploadPath+filename));
            }
        }
        return "redirect:/seller/render.htm";
    }

    @RequestMapping("/categorySkuStatus")
    @ResponseBody
    public String categorySkuStatus(@RequestParam("cid") int cid){
        // sku 列表
        List<SkuKey> skuLists = attributeService.findSkuListById(cid);
        System.out.println("我的长度："+skuLists.size());
        //五次分类，循环五次查找父级属性
        if(skuLists.size() > 0){
            return "false";
        }

        for (int i = 0; i < 5; i++) {
            skuLists = attributeService.findSkuListById(cid);
            if (skuLists.size() > 0) {
                return "false";
            }

            int parentId = getParentCategoryId(cid);
            cid = parentId;
            // 如果是空
            if(cid == 99999){
                skuLists = null;
                return "true";
            }
        }
        return "true";
    }

    /**
     * 获取商品类别父节点ID
     * @param cid
     * @return
     */
    public int getParentCategoryId(int cid){
        int parentId = 0;
        try {
            Category category = categoryService.byIdFindCategory(cid);
            String[] paths = category.getPath().split(",");
            parentId = Integer.parseInt(paths[paths.length-1]);
        } catch (NullPointerException e){
            return 99999;
        }
        return parentId;
    }
}
